import { storeBindingsBehavior } from "mobx-miniprogram-bindings";
import payBehavior from "./payBehavior";
import {
  cancelOrder,
  getAppointmentShopDetail,
  getOrderDetail,
  delOrder,
  editOrderReservationTime,
  autoCancel,
} from "@src/api/reservation";
import {
  RESERVATION_PAY_TYPE,
  RESERVATION_PAY_TYPE_TEXT,
  DISCOUNT_TYPE,
  DISCOUNT_TYPE_TEXT,
  RESERVATION_ORDER_STATE,
  RESERVATION_ORDER_STATE_TEXT,
  PAYMENT_STATUS,
  PROJECT_TYPE,
} from "@src/sp-reservation/constant/index.js";
import {
  copyClipboard,
  getPayChannels,
  getWriteOffQrCode,
  handleCheckAllowedPwd,
} from "../../../common/reservation/config/index";
import router from "@src/router";
import reservation from "@src/store/reservation";
import location from "@src/store/location";
import dayjs from "dayjs";
import base from "@src/store/base";
Page({
  behaviors: [storeBindingsBehavior, payBehavior],
  storeBindings: [
    {
      store: location,
      fields: ["latitude", "longitude"],
      actions: ["getLocation", "showAuthTip"],
    },
    {
      store: base,
      fields: ["isiPhoneX", "themeColor", "themeTitleColor"],
    },
  ],
  data: {
    //路由信息
    options: {},
    //order信息
    orderDetail: {},
    totalFee: 0,
    pay_text: RESERVATION_PAY_TYPE_TEXT[RESERVATION_PAY_TYPE.ON_LINE],
    //优惠券
    isShowCouponSelect: false,
    couponsList: [],
    DISCOUNT_TYPE,
    DISCOUNT_TYPE_TEXT,
    RESERVATION_ORDER_STATE,
    RESERVATION_ORDER_STATE_TEXT,
    RESERVATION_PAY_TYPE,
    RESERVATION_PAY_TYPE_TEXT,
    PAYMENT_STATUS,
    //商品信息
    goodsInfo: {},
    //店铺信息
    shopInfo: {},
    //其他信息
    newDate: "",
    isShowQRPopup: false,
    isShowTimeSelect: false,
    showDetail: false,
    qrUrl: "",
    payChannels: [],
    whiteTiemEnd: null,
    remaiPayTime: null,
    timer: null,
    isShowFooter: false,
    loading: false,
  },
  onLoad: function (options) {
    wx.showLoading();
    this.setData({
      options,
    });
    // this.fetchData();
  },

  onPullDownRefresh() {
    wx.showLoading({ title: "加载中" });
    this.setData({ loading: true });
    this.fetchData();
  },
  onLogin() {
    this.getLocation(true)
      .then((res) => {
        if (this.data.options.shopId) {
          this.setData({ latitude: res.latitude, longitude: res.longitude });
          this.fetchData();
        }
      })
      .catch((res) => {
        if (this.data.options.shopId) {
          this.fetchData();
        }
      });
  },
  async handleCheckCancelOrder() {
    const {
      orderVo: { payDeadline },
      status,
      orderNo,
      paymentType,
    } = this.data.orderDetail;
    const lastTime = new Date(payDeadline).getTime();
    const nowTime = Date.now();
    if (
      paymentType === RESERVATION_PAY_TYPE.ON_LINE &&
      status === RESERVATION_ORDER_STATE.WAIT_PAY &&
      nowTime > lastTime
    ) {
      const { cancelOrderTime } = this.data.orderDetail;
      if (cancelOrderTime === 0) return;
      //超时取消订单
      const { code } = await autoCancel({
        orderNo,
      });
      if (code === 0) {
        await this.fetchData();
      }
    }
  },
  getPayDeadline(res) {
    const self = this;
    let startTime = dayjs(new Date()).valueOf() || "";
    const {
      orderVo: { payDeadline },
    } = this.data.orderDetail;
    let endTime = new Date(payDeadline.replace(/\-/g, "/")).getTime() || "";
    let dis = endTime - startTime; // 相差的毫秒数;
    //如果倒计时小于0，设置状态为过期
    if (dis < 0) {
      this.handleCheckCancelOrder();
      clearInterval(this.data.timer);
      this.setData({ whiteTiemEnd: true, timer: null });
      this.fetchData();
    }
    let s = 0; // 秒
    let m = 0; // 分钟
    let h = 0; // 小时
    let d = 0; // 天
    if (dis > 0) {
      dis = Math.floor(dis / 1000);
    }
    if (dis > 0) {
      s = dis % 60;
      dis = Math.floor(dis / 60);
    }
    if (dis > 0) {
      m = dis % 60;
      dis = Math.floor(dis / 60);
    }
    if (dis > 0) {
      h = dis % 60;
      dis = Math.floor(dis / 60);
    }
    if (dis > 0) {
      d = dis % 24;
    }
    this.setData({
      remaiPayTime:
        h > 0 ? h + "小时" + m + "分钟" + s + "秒" : m + "分钟" + s + "秒",
    });
  },
  async fetchData() {
    const {
      options: { orderNo, shopId },
    } = this.data;
    //获取门店信息
    const { code, data } = await getAppointmentShopDetail({ shopId });
    const { code: orderCode, data: orderData } = await getOrderDetail({
      orderNo,
      shopId,
    });
    if (code === 0) {
      this.setData({
        shopInfo: data,
      });
    }
    if (orderCode === 0 && orderData) {
      wx.hideLoading();
      wx.stopPullDownRefresh();
      this.setData({ loading: false });
      //删除订单直接退出到我的订单
      if (orderData?.userDeleted) {
        router.push({
          name: "member/myOrderList",
        });
        return;
      }
      // if (orderData?.orderVo?.userDeleted) {
      //   router.push({
      //     name: "member/myOrderList",
      //   });
      //   return;
      // }
      if (orderData?.goodsVOList.length > 0) {
        orderData.goodsVOList.map((v) => {
          v.skuInfo = JSON.parse(v.skuInfo);
        });
      }
      this.setData({
        orderDetail: orderData,
        showDetail: true,
        isShowFooter:
          orderData.status === RESERVATION_ORDER_STATE.WAIT_PAY ||
          (orderData.status === RESERVATION_ORDER_STATE.CANCEL &&
            orderData.paymentType === RESERVATION_PAY_TYPE.ON_LINE &&
            orderData.orderVo.paymentStatus ===
              PAYMENT_STATUS.RETURN_SUCCESS) ||
          orderData.status === RESERVATION_ORDER_STATE.WAIT_SERVICE ||
          orderData.status === RESERVATION_ORDER_STATE.FINISH ||
          orderData.status === RESERVATION_ORDER_STATE.CLOSE,
      });
      this.handleCheckCancelOrder();
      console.log("orderData", this.data.isShowFooter, orderData.status);
      const { status } = this.data.orderDetail;
      if (status === RESERVATION_ORDER_STATE.WAIT_PAY) {
        this.getPayDeadline();
        const timer = setInterval(() => {
          this.getPayDeadline();
        }, 1000);
        this.setData({
          timer,
        });
      }
    } else {
      this.setData({
        showDetail: false,
      });
      wx.hideLoading();
      wx.showToast({
        title: "暂无订单数据",
        icon: "none",
        duration: 2000,
        success() {
          setTimeout(() => {
            router.push({
              name: "member/myOrderList",
            });
          }, 1500);
        },
      });
    }
  },
  handleToMap() {
    const {
      shopInfoResp: { latitude, longitude, shopName, address },
    } = this.data.shopInfo;
    wx.openLocation({
      latitude,
      longitude,
      name: shopName,
      address,
      scale: 18,
    });
  },
  //去支付
  async handlePay() {
    const payChannels = getPayChannels(this.data.orderDetail.payChannels);
    this.setData({
      payChannels,
    });
    const {
      orderNo,
      orderVo: { payFee },
    } = JSON.parse(JSON.stringify(this.data.orderDetail));
    //新增初始化会员密码操作
    const { accountPayRule } = this.data;
    const initialed = await handleCheckAllowedPwd(payFee, accountPayRule);
    if (!initialed) return;
    this.toPay({
      orderNo,
      payFee,
      maxPayLatency: 300,
    })
      .then(() => {
        const { orderDetail, shopInfo } = this.data;
        router.redirectTo({
          // name: "reservation/reservation_order_detail",
          name: "reservation/reservation_success",
          params: {
            ...orderDetail,
            shopId: shopInfo.shopInfoResp.shopId,
          },
        });
        // this.fetchData();
      })
      .catch(() => {
        this.fetchData();
      });
  },
  //去核销
  async handleWriteOff() {
    wx.showLoading({
      title: "加载核销码中",
    });
    const writeOffCode = this.data.orderDetail.writeOffCode;
    console.log("writeOffCode", writeOffCode);
    if (!writeOffCode) {
      wx.hideLoading();
      return;
    }
    getWriteOffQrCode(writeOffCode).then((qrUrl) => {
      wx.hideLoading();
      if (qrUrl) {
        this.setData({
          qrUrl,
        });
        this.setData({
          isShowQRPopup: true,
        });
      }
    });
  },
  //修改预约
  handleEdit() {
    this.setData({
      isShowTimeSelect: true,
    });
  },
  handleCloseSelectTime() {
    this.setData({
      isShowTimeSelect: false,
    });
  },
  handleSelectDateTime(e) {
    const { detail } = e;
    const time = `${detail.date.value} ${detail.time.time}`;
    this.setData({
      newDate: time,
    });
    console.log("选择了时间", e);
  },
  handleToShopHome(e) {
    router.push({
      name: "reservation/home",
      params: {
        shopId: this.data.shopInfo.shopInfoResp.shopId,
      },
    });
  },
  handleConfirmSelect() {
    wx.showModal({
      title: "提示",
      content: "确定要修改预约时间吗？",
      success: async (res) => {
        if (res.confirm) {
          const { orderNo } = this.data.orderDetail;
          const { newDate } = this.data;
          editOrderReservationTime({
            orderNo,
            newDate,
          })
            .then((res) => {
              const { code } = res;
              if (code === 0) {
                wx.showToast({
                  title: "修改成功",
                  icon: "none",
                });
                this.handleCloseSelectTime();
                this.fetchData();
              }
            })
            .catch((err) => {
              console.log("失败========", err);
              const {
                data: { msg },
              } = err;
              wx.showToast({
                title: msg,
                icon: "none",
                duration: 1500,
              });
            });
        }
      },
    });
  },
  //删除订单
  handleDel() {
    wx.showModal({
      title: "提示",
      content: "确定要删除订单吗？",
      success: async (res) => {
        if (res.confirm) {
          const { orderNo } = this.data.orderDetail;
          const { code } = await delOrder({
            orderNo,
          });
          if (code === 0) {
            wx.showToast({
              title: "删除成功",
              icon: "none",
            });
            router.back();
          }
        }
      },
    });
  },
  //取消订单
  handleCancel() {
    wx.showModal({
      title: "提示",
      content: "确定要取消订单吗？",
      success: async (res) => {
        if (res.confirm) {
          const { orderNo } = this.data.orderDetail;
          const { code } = await cancelOrder({
            orderNo,
            reason: "用户确认自己取消",
            param0: orderNo,
          });
          if (code === 0) {
            wx.showToast({
              title: "取消成功",
              icon: "none",
            });
            this.fetchData();
          }
        }
      },
    });
  },
  handleToCancelDetail() {
    const { orderNo } = this.data.orderDetail;
    router.push({
      name: "reservation/return_good_detail",
      params: {
        orderNo,
      },
    });
  },
  handleToProjectDetail(e) {
    const {
      currentTarget: {
        dataset: { item },
      },
    } = e;
    const {
      shopInfo: { shopInfoResp },
      orderDetail: { appointmentPlanId },
    } = this.data;
    router.push({
      name: `reservation/project_detail`,
      params: {
        id: item.id,
        planId: appointmentPlanId,
        shopId: shopInfoResp.shopId,
        shopConfigId: shopInfoResp.shopConfigId,
        goodsSerial: item.goodsSerial,
      },
    });
  },
  handleCloseQRCode() {
    this.setData({
      qrUrl: "",
      isShowQRPopup: false,
    });
  },
  handleCopy(e) {
    // copyClipboard(e.currentTarget.dataset.no);
    wx.setClipboardData({
      data: e.currentTarget.dataset.no,
      showToast: false,
      success: function (res) {
        wx.hideToast();
        wx.nextTick(() => {
          wx.showToast({
            title: "复制成功",
          });
        });
      },
    });
  },
});
